﻿using AutoMapper;
using B.S.Traceability.Domain;
using B.S.Traceability.Error;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Writer.API.Application.Commends.Company;
using MediatR;

namespace B.S.Traceability.Writer.API.Application.CommendHandlers.Company
{
    public class CreateCompanysCommendHandlers : IRequestHandler<CreateCompanysCommends, APIResult<Companys>>
    {
        private readonly IBaseRepository<Companys> companysRepository;
        private readonly IMapper mapper;

        public CreateCompanysCommendHandlers(IBaseRepository<Companys> companysRepository, IMapper mapper)
        {
            this.companysRepository = companysRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加企业信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<Companys>> Handle(CreateCompanysCommends request, CancellationToken cancellationToken)
        {
            APIResult<Companys> result = new APIResult<Companys>();

            var exit =  companysRepository.GetAllAsync().Result.FirstOrDefault(x => x.CompanyId == request.CompanyId);
            if (exit == null)
            {
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";

                var farm = mapper.Map<Companys>(request);
                farm.BatchId = request.BatchId;
                farm.IsDel = false;
                await companysRepository.Add(farm);

            }
            else
            {
                mapper.Map(request,exit);

                result.Code = APIEnum.修改成功;
                result.Msg = "修改成功";

     
                await companysRepository.Update(exit);
            }
         
            return await Task.FromResult(result);
        }
    }
}
